<template>
  <div class="app-container">
    <search-box :isMulti="false">
      <template slot="content">
        <div class="left-box">

          <el-form-item label="产品名称：">
            <el-input v-model="listQuery.proName"
                      placeholder="请输入"
                      clearable/>
          </el-form-item>


        </div>
        <div class="right-box">
          <el-button size="mini" type="success"
                     @click="handleCreate">新增
          </el-button>

          <el-button size="mini"
                     @click="handleFilter">查询
          </el-button>
          <el-button size="mini" type="info"
                     @click="reset">重置
          </el-button>
        </div>
      </template>
    </search-box>
    <div class="table-wrap">
      <el-table :data="list"
                style="width:100%"
                element-loading-text="Loading"
                height="600"  width="150">
        <el-table-column
          type="index"
          width="50"
          label="序号"
        ></el-table-column>
        <el-table-column prop="proCode"
                         label="产品编码" >
        </el-table-column>

        <el-table-column prop="proBrand"
                         label="产品品牌" >
        </el-table-column>

        <el-table-column prop="proName"
                         label="产品名称">
        </el-table-column>
        <el-table-column prop="proPrice"
                         label="产品价格" >

          <template slot-scope="scope">
            <div >
              ￥{{scope.row.proPrice.toFixed(2)}}{{scope.row.proUnit}}
            </div>
          </template>

        </el-table-column>
        <el-table-column prop="proTypeName"
                         label="产品类型" >
        </el-table-column>
        <el-table-column prop="proTime"
                         label="生产日期">

          <template slot-scope="scope">
            <div >

              {{scope.row.proTime.substring(0,10)}}

            </div>
          </template>

        </el-table-column>


        <el-table-column prop="proPlace"
                         label="产品产地" width="300">
          <template slot-scope="scope">
            <div >
              {{scope.row.proPlace.replaceAll(' ','')}}
            </div>
          </template>

        </el-table-column>


        <el-table-column prop="proPeople"
                         label="生产厂家"  >
        </el-table-column>


<!--        <el-table-column prop="createDate"-->
<!--                         label="创建时间" value-format="yyyy-MM-dd">-->
<!--        </el-table-column>-->
        <el-table-column label="操作"
                         width="200">
          <template slot-scope="scope">
            <div class="scope-operate">
              <el-button type="info" size="mini" @click="handleUpdate(scope.row)">编辑
              </el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除
              </el-button>

            </div>
          </template>
        </el-table-column>


      </el-table>







      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="listQuery.pageNumber"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getList"/>
    </div>


    <!--    //dialog弹窗 在页面的最后一个</div>的上面-->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      style="margin-top: -6%"
      width="60%"
      :before-close="handleClose"
      >
      <el-form ref="form" :model="form" :rules = 'rules' label-width="100px">
        <el-form-item   label-width="0px">
          <el-col :span="12">
              <el-form-item label="产品编码" prop="proCode">
                <el-input v-model="form.proCode"></el-input>
              </el-form-item>
          </el-col>
            <el-col :span="12">
              <el-form-item label="产品名称" prop="proName">
                <el-input v-model="form.proName"></el-input>
              </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item   label-width="0px">
          <el-col :span="6">
              <el-form-item label="产品价格" prop="proCode">
                <el-input v-model="form.proPrice"></el-input>
              </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品规格" prop="proUnit">
              <el-select v-model="form.proUnit" placeholder="请选择产品规格">
                <el-option
                  v-for="item in proUnitList"
                  :key="index"
                  :label="item.unitName"
                  :value="item.unitName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="库存量" prop="proInventory">
              <el-input v-model="form.proInventory"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="销售量" prop="proSale">
              <el-input v-model="form.proSale"></el-input>
            </el-form-item>
          </el-col>

        </el-form-item>


        <el-form-item label="产品简介" prop="proBrief">
          <el-input v-model="form.proBrief"></el-input>
        </el-form-item>

        <el-form-item label="产品功能" prop="proDesc">
          <div class="edit_container">
            <quill-editor v-model="form.proDesc" ref="myQuillEditor" class="editer" :options="editorOption" @ready="onEditorReady($event)">
            </quill-editor>
          </div>
        </el-form-item>







        <el-form-item label-width="0">
        <el-col :span="5">
        <el-form-item label="产地省份" prop="provinceName">
          <el-select v-model="form.provinceName" placeholder="请选择" @change="getCityInfoList" id="provinceName">
            <el-option
              v-for="item in areaInfoList"
              :key="item.areaName"
              :label="item.areaName"
              :value="item.areaName">
            </el-option>
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="5">
        <el-form-item label="产地城市" prop="cityName">
          <el-select v-model="form.cityName" placeholder="请选择" @change="getCountyInfoList" id="cityName">
            <el-option
              v-for="item in cityInfoList"
              :key="item.areaName"
              :label="item.areaName"
              :value="item.areaName">
            </el-option>
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="5">
        <el-form-item label="产地区划" prop="countyName">
          <el-select v-model="form.countyName" placeholder="请选择" id="countyName">
            <el-option
              v-for="item in countyInfoList"
              :key="item.areaName"
              :label="item.areaName"
              :value="item.areaName">
            </el-option>
          </el-select>
        </el-form-item>
        </el-col>
          <el-col :span="9">
            <el-form-item label="详细产地" prop="detailAddress">
              <el-input v-model="form.detailAddress"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label-width="0">
          <el-col :span="12">

            <el-form-item label="产品品牌" prop="proCode">
              <el-input v-model="form.proBrand"></el-input>
            </el-form-item>
          </el-col>
            <el-col :span="12">
              <el-form-item label="生产日期" prop="proCode">
                <el-date-picker type="date" placeholder="选择日期" v-model="form.proTimeStr" style="width: 100%;" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
        </el-form-item>



        <el-form-item label-width="0">

          <el-col :span="12">
            <el-form-item label="产品类型" prop="proTypeCode">
            <el-select v-model="form.proTypeCode" placeholder="请选择产品类型">


              <el-option
                v-for="item in productTypeList"
                :key="index"
                :label="item.proTypeName"
                :value="item.proTypeCode">
              </el-option>

            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产厂家" prop="proPeople">
              <el-input v-model="form.proPeople"></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="产品图片" prop="proUrl">
          <el-upload
            class="upload-demo"
            :action="processBaseUrl"
            :on-success="handleSuccess"
            :file-list="fileList"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible1">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">提 交</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">

  </span>

    </el-dialog>



    <!--    //dialog弹窗 在页面的最后一个</div>的上面-->
    <el-dialog
      title="产品详情"
      :visible.sync="dialogVisibleDesc"
      width="60%"
      >

      <div v-html="proInfo.proDesc">
        {{proInfo.proDesc}}
      </div>

    </el-dialog>


  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { quillEditor } from 'vue-quill-editor'//添加富文本编辑器
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'

  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  // 当然你也可以为了方便使用，将它注册到全局
  import bus from '@/utils/eventBus'
  import searchBox from '@/components/searchBox.vue'
  import * as product from '@/api/product/product'
  import * as productType from '@/api/product/productType'
  import * as areaInfo from '@/api/area/areaInfo'

  import * as proutil from '@/api/product/proutil'


  export default {
    name: 'AdminUser',
    components: { Pagination, searchBox, quillEditor },
    directives: { waves },
    filters: {},
    data() {
      return {
        dialogVisible1: false,
        dialogImageUrl: '',
        fileList: [],
        content: '',
        editorOption: {},
        list: null,
        areaInfoList: null,
        cityInfoList: null,
        countyInfoList: null,
        productTypeList: null,
        areaList: null,
        total: 0,
        processBaseUrl: process.env.VUE_APP_BASE_API+'/file/upload',
        listQuery: { // 查询列表时的参数对象
          pageNumber: 1,
          pageSize: 50,
          appName: process.env.VUE_APP_APP_NAME,
          tenantIdList: []
        },
        dialogVisible: false,
        dialogVisibleDesc: false,
        dialogTitle:'',
        form:{
          proDesc: 'proDesc',
          proTimeStr: '',
          provinceCode:'',

        },

        proInfo:{

        },



        proUnitList:[

          ],

        rules: {
          proCode: [{ required: true, message: '产品编码必填', trigger: 'blur' }],
          proName: [{ required: true, message: '产品名称必填', trigger: 'blur' }],
          proPrice: [{ required: true, message: '产品价格必填', trigger: 'blur' }],
          proTime: [{ required: true, message: '产品时间必填', trigger: 'blur' }],
          proBrand: [{ required: true, message: '产品品牌必填', trigger: 'blur' }],
          proTypeCode: [{ required: true, message: '产品类型编码必选', trigger: 'blur' }],
          proUnit: [{ required: true, message: '产品规格必选', trigger: 'blur' }],
          provinceName: [{ required: true, message: '省份必选', trigger: 'blur' }],
          cityName: [{ required: true, message: '城市必选', trigger: 'blur' }],
          countyName: [{ required: true, message: '区划必选', trigger: 'blur' }],
          detailAddress: [{ required: true, message: '详细地址必填', trigger: 'blur' }],
          proPeople:  [{ required: true, message: '生产厂家必填', trigger: 'blur' }],
          proBrief:  [{ required: true, message: '产品简介必填', trigger: 'blur' }],
          proInventory:  [{ required: true, message: '库存量必填', trigger: 'blur' }],
          proSale:  [{ required: true, message: '销售量必填', trigger: 'blur' }],
        }
      }
    },
    computed: {
      ...mapGetters([
        'selectedTenantId',
        'tenantList'
      ])
    },
    created() {

      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
      this.getList()

      // 监听 租户改变的事件,选择不同租户后,立马刷新数据
      bus.$on('selectedTenantIdChanged', () => {
        console.log('selectedTenantIdChanged事件触发...')
        this.getList()
      })
    },
    mounted() {

    },
    beforeDestroy() { // 当路由切换到其他页面时触发
      bus.$off('selectedTenantIdChanged')
    },
    methods: { //所有的方法写在当前钩子函数下

      onEditorReady(editor) {
      },

      async getList() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        const { content } = await product.getProductList(this.listQuery)
        this.list = content.list
        this.total = content.totalCounts
      },

      async getAreaInfoList() {// 获取省列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        let query = {};
        const { content } = await areaInfo.getAreaInfoListNoPage(query);
        this.areaInfoList = content //分页的时候是content.list;不分页的时候是content 因为不分页的时候少封装一层
        query = {};
      },

      async getCityInfoList() {// 获取市列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        let query = {};
        if(this.form.provinceName != null){
          query.parentName = this.form.provinceName;
        }
        const { content } = await areaInfo.getAreaInfoListNoPage(query);
        this.cityInfoList = content //分页的时候是content.list;不分页的时候是content 因为不分页的时候少封装一层
        query = {};
      },
      async getCountyInfoList() {// 获取区列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        let query = {};
        if(this.form.cityName!=null){
          query.parentName = this.form.cityName;
        }
        const { content } = await areaInfo.getAreaInfoListNoPage(query);
        this.countyInfoList = content //分页的时候是content.list;不分页的时候是content 因为不分页的时候少封装一层
        query = {};
      },


      async getProductTypeList() { // 获取产品类型列表数据 异步加载 假如数据量很大 先不加载数据 先加载dom(html) 等html加载完成了 再加载数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        const { content } = await productType.getProductTypeList(this.listQuery)
        this.productTypeList = content.list;
        console.log(this.dialogTitle,this.productTypeList);
      },

      handleFilter() {
        this.listQuery.pageNumber = 1
        this.getList()
      },

      handleClose(){
        this.dialogVisible = false;
        this.fileList=[]
      },

      //新增数据
      handleCreate() {
        this.form={}
        this.dialogVisible = true
        this.dialogTitle='新增'
        this.form.provinceName = null
        this.getProductTypeList();
        this.getAreaInfoList();
        this.getUnitList();

      },
      //编辑数据
      handleUpdate(row) {
        this.fileList=[];
        this.dialogVisible = true
        this.dialogTitle='编辑';
        this.form = row;
        let proPlace = row.proPlace.split(" ");
        // document.getElementById("provinceName").value = proPlace[0];
        // document.getElementById("cityName").value = proPlace[1];
        // document.getElementById("countyName").value = proPlace[2];


        this.$set(this.form,'proTimeStr',row.proTime);
        this.$set(this.form,'provinceName',proPlace[0]);
        this.$set(this.form,'cityName',proPlace[1]);
        this.$set(this.form,'countyName',proPlace[2]);
        this.$set(this.form,'detailAddress',proPlace[3]);


        if(row.proUrl!=null&&row.proUrl!=''){

          let fileUrl = row.proUrl.split(",");
          let proFileName = row.proFileName.split(",");


          for(let i = 0;i<fileUrl.length;i++){
            let imageInfo = {

            }
            imageInfo.url=process.env.VUE_APP_BASE_API+'/file/downloadFile?fileName='+fileUrl[i]
            imageInfo.name=proFileName[i]
            this.fileList.push(imageInfo);
          }
        }else{
          this.fileList=[]
        }

        console.log(this.fileList)

        this.form.detailAddress = proPlace[3];
        this.getProductTypeList();
        this.getAreaInfoList();
        this.getUnitList();
      },
      //删除数据
      handleDelete(row) {

        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          product.deleteProduct(row).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }).catch(() => {
        })
      },


      handleLookProInfo(row){
        let proDesc = row.proDesc;
        this.dialogVisibleDesc = true;
        this.proInfo = row;
      },

      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleSuccess(response, file, fileList) {

      console.log(this.fileList);
        console.log('文件成功列表',fileList);
        let proUrl = '';
        let proFileName = '';
        for(let i = 0;i<fileList.length;i++){
          proUrl+=(fileList[i].response.uuid+',')
          proFileName+=(fileList[i].response.name+',')
        }
        this.form.proUrl = proUrl.substring(0,proUrl.length-1)
        this.form.proFileName = proFileName.substring(0,proFileName.length-1)
      },

      //页面表单提交
      onSubmit(){
        let provinceName =null;
        let cityName =null;
        let countyName =null;
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.form.tenantId = this.$store.getters.selectedTenantId
            // this.form.proTime = this.form.proTimeStr;
            debugger
            provinceName =  document.getElementById("provinceName").value;
            cityName =  document.getElementById("cityName").value;
            countyName =  document.getElementById("countyName").value;


            this.form.proPlace='';
            if(provinceName!=null||provinceName!=undefined){
              this.form.proPlace += (provinceName+" ");
            }
            if(cityName!=null||cityName!=undefined){
              this.form.proPlace += (cityName+" ");
            }
            if(countyName!=null||countyName!=undefined){
              this.form.proPlace += (countyName+" ");
            }
            if(this.form.detailAddress!=null||this.form.detailAddress!=undefined){
              this.form.proPlace += this.form.detailAddress;
            }
            if (this.dialogTitle == '新增') {
              product.createProduct(this.form).then((res) => {
                console.log(res)
                if (res.status == 200) {
                  this.$notify({
                    title: '成功',
                    message: '添加成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.dialogVisible = false
                  this.getList()

                }
              })

            } else if (this.dialogTitle == '编辑') {

              product.updateProduct(this.form).then((res) => {
                console.log(res)
                if (res.status == 200) {
                  this.$notify({
                    title: '成功',
                    message: '编辑成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.dialogVisible = false
                  this.getList()
                  this.fileList=[];

                }
              })


            }
            provinceName =  null
            cityName =  null
            countyName =  null
          } else {
            console.log('error submit!!')
            return false
          }
        })


      },
      async getUnitList() { // 获取列表数据
        this.listQuery.tenantIdList = []
        if (this.selectedTenantId == undefined) {//当前选中所有的租户
          this.tenantList.forEach((tenant, index) => {
            this.listQuery.tenantIdList.push(tenant.id)
          })
        } else {
          this.listQuery.tenantIdList.push(this.selectedTenantId)
        }
        const { content } = await proutil.getProUtilListCount(this.listQuery)
        this.proUnitList = content
        console.log(this.proUnitList);
      },

      cancel(){
        this.dialogVisible = false;
        this.form = {};
        this.fileList=[];
              },
      reset() {
        this.listQuery = {}
        this.getList()
      }
    }
  }
</script>

<style scoped>
  .app-select {
    margin-bottom: 20px;
  }
</style>
